// app.js
import Http from "./utils/http";
App({
    // 用户标识存储
    userData: {
        userId: null,
        sessionId: null,
        lastActiveTime: 0
    },
    onLaunch() {
        console.log('小程序启动');
        wx._baseUrl = new Http()._baseUrl;
        wx.Http = new Http(); //全局
        //默认自动登录
        // 微信授权登录
        //没有token会走这里
        let _this = this;
        if (wx.getStorageSync("token").length == 0) {
            let mytoken = this.globalData.mytoken;
            if (mytoken) {
                console.log("重复创建token了")
            } else {
                wx.login({
                    success: (res) => {
                        if (res.errMsg == "login:ok") {
                            // let mytoken = this.globalData.mytoken;
                            // if (mytoken) {
                            //     console.log("出现重复请求token1")
                            // } else {
                            // getApp().globalData.mytoken = true;
                            wx.Http.post("/UserAccountAppService/Xncf.Xxgmall_UserAccountAppService.GetOpenId", {
                                code: res.code,
                            }).then((res) => {
                                if (res.success == true) {
                                    console.log("测试第一个地点")
                                    // wx.role= res.data.value.role
                                    wx.setStorageSync('userId', res.data.value.userId)
                                    wx.setStorageSync("token", res.data.value.token);
                                    this.sequentialAPIs();


                                    // setTimeout(() => {
                                    //     this.initUserSession();
                                    // }, 200);
                                    // setTimeout(() => {
                                    //     wx.Http.post("/AccountAppService/GetUserinfo", {}).then((res) => {
                                    //         if (res.data?.value) {
                                    //             wx.setStorageSync("Monkey", res.data.value);
                                    //             getApp().globalData.mytoken = false;
                                    //             console.log("mytoken" + console.log("mytoken" + getApp().globalData.mytoken))
                                    //         }
                                    //     });
                                    // }, 500);
                                } else this.stopHeartbeat();
                            });
                            // }

                        }
                    },
                });

            }

        } else {
            this.sequentialAPIs();
            console.log("启动")
        }

        {
            // setTimeout(() => {
            //     wx.Http.post("/AccountAppService/GetUserinfo", {}).then((res) => {
            //         if (res.data?.value) {
            //             wx.setStorageSync("Monkey", res.data.value);
            //         }
            //     });
            // }, 200);

        }
    },
    async sequentialAPIs() {
        try {
            const loginRes = await this.initUserSession();
            const requestRes = await this.showme();
            console.log('顺序执行完成');
        } catch (err) {
            console.error('执行失败', err);
        }
    },
     // 初始化用户会话
     initUserSession() {
        // 尝试获取本地存储的用户ID
        const storedUserId = wx.getStorageSync('userId')
        const sessionId = this.generateSessionId()
        if (storedUserId) {
            this.userData.userId = storedUserId
            this.userData.sessionId = sessionId
            this.updateUserActivity('resume')
        } else {
            this.userData.sessionId = sessionId
            this.updateUserActivity('new')
        }
    },
    showme() {
        // 恢复心跳
        if (!this.heartbeatTimer) {
            // this.startHeartbeat()
        }
        // 记录打开事件
        this.recordAppOpen()
    },
    onShow() {

    },

    onHide() {
        // 暂停心跳以节省资源
        this.stopHeartbeat()
    },

   
    // 生成唯一会话ID
    generateSessionId() {
        return 'sess_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
    },

    // 记录应用打开事件
    recordAppOpen() {
        try {
            wx.Http.post("/GetDashboardStatsAppService/Xncf.Xxgmall_GetDashboardStatsAppService.RecordOpen", {
                userId: this.userData.userId,
                sessionId: this.userData.sessionId,
                timestamp: Date.now()
            }).then((res) => {
                if (res.success) {
                    console.log("记录应用打开事件")
                } else if (res.success == false) {
                    this.stopHeartbeat()
                }
            })
        } catch (error) {
            this.stopHeartbeat()
        }


    },

    // 更新用户活跃状态
    updateUserActivity(type = 'active') {
        const now = Date.now()
        this.userData.lastActiveTime = now
        try {
            wx.Http.post("/UserActivityAppService/Xncf.Xxgmall_UserActivityAppService.UpdateActivity", {
                type: type,
                userId: this.userData.userId,
                sessionId: this.userData.sessionId,
                // timestamp: now
            }).then((res) => {
                if (res.success) {
                    console.log('更新用户活跃状态');
                    // 如果是新用户，保存用户ID
                    if (res.data.userId && !this.userData.userId) {
                        this.userData.userId = res.data.userId
                        wx.setStorageSync('userId', res.data.userId)
                    }
                } else if (res.success == false) {
                    this.stopHeartbeat()
                }
            })
        } catch (error) {
            this.stopHeartbeat()
        }


    },

    // 开始心跳定时器
    startHeartbeat() {
        // 每分钟发送一次心跳
        this.heartbeatTimer = setInterval(() => {
            // console.log('开始心跳定时器');
            this.updateUserActivity()
        }, 60000) // 60秒

        // 立即发送一次心跳
        // this.updateUserActivity()
    },

    // 停止心跳
    stopHeartbeat() {
        if (this.heartbeatTimer) {
            console.log("停止心跳")
            clearInterval(this.heartbeatTimer)
            this.heartbeatTimer = null
        }
    },

    // 标记用户为已注册
    // markUserRegistered() {
    //     if (!this.userData.userId) return

    //     wx.request({
    //         url: `${API_BASE}/user/register`,
    //         method: 'POST',
    //         data: {
    //             userId: this.userData.userId,
    //             timestamp: Date.now()
    //         }
    //     })
    // },
    globalData: {
        currentTab: 0, // 当前选中的tab索引
        tabBarRoutes: {
            'pages/index/index': 0,
            'pages/cart/cart': 1,
            'pages/order/order': 2, // 订单页面
            'pages/my/my': 3
        }
    },

    // 设置当前tab
    setCurrentTab(index) {
        console.log('设置当前tab:', index);
        this.globalData.currentTab = index;

        // 同时更新tabBar组件的状态
        const tabBar = this.getTabBar();
        if (tabBar) {
            tabBar.setData({ current: index });
        }
    },

    // 获取当前tab
    getCurrentTab() {
        return this.globalData.currentTab;
    },

    // 根据页面路径获取tab索引
    getTabIndexByPath(path) {
        return this.globalData.tabBarRoutes[path] || 0;
    },
    // 全局的getTabBar函数 - 安全版本
    getTabBar() {
        try {
            const pages = getCurrentPages();
            if (pages.length === 0) {
                console.log('没有页面栈');
                return null;
            }

            const currentPage = pages[pages.length - 1];
            if (!currentPage) {
                console.log('当前页面不存在');
                return null;
            }

            // 使用selectComponent获取tabBar组件实例
            const tabBar = currentPage.selectComponent('#custom-tab-bar');
            if (!tabBar) {
                console.log('未找到custom-tab-bar组件');
                return null;
            }

            return tabBar;
        } catch (error) {
            console.error('获取tabBar失败:', error);
            return null;
        }
    },
    onShow: function (option) {
        console.log("进入" + option)
        debugger
        if (option?.query?.scene) {
            setTimeout(() => {
                if (option?.query?.scene.indexOf("HRid") !== -1) {
                    const parts = option.query.scene.split(/HRid|%23/);
                    wx.setStorageSync("HRid", parts[1]);
                    console.log("获取到二维码的悬赏码" + parts[1])
                } else if (option?.query?.scene.indexOf("UId") !== -1) {
                    // const parts = options.scene.match(/UId(\d+)(?:#|%23)/);
                    const parts = option?.query?.scene.split(/UId|%23/);
                    wx.setStorageSync("HRid", parts[1]);
                    console.log("获取到二维码的悬赏码" + parts[1])
                }
            }, 2000);

            // wx.setStorageSync("HRid", option?.query?.scene);
        }
        if (option?.query?.hrCode) {
            setTimeout(() => {
                wx.setStorageSync("HRid", option?.query?.hrCode);
                console.log("获取到链接的悬赏码" + option?.query?.hrCode)
            }, 2000);

        }
        // updateManager();
        // this.onLaunch()
    },

    // 更新当前页面对应的tab状态
    updateTabBarForCurrentPage() {
        try {
            const pages = getCurrentPages();
            if (pages.length === 0) return;

            const currentPage = pages[pages.length - 1];
            const route = currentPage.route;
            const tabIndex = this.getTabIndexByPath(route);

            this.setCurrentTab(tabIndex);
        } catch (error) {
            console.error('更新tabBar状态失败:', error);
        }
    },


})
